package com.ziyun.pop.common.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.ziyun.pop.common.token.RedisTokenManager;

import io.renren.common.utils.HttpContextUtils;
import io.renren.modules.sys.entity.SysUserEntity;

/**
 * @author guizhao
 * @Description: 用户具类
 * @date 2018-08-0413:27
 */
@Component
public class UserUtils implements ApplicationContextAware {
	private static ApplicationContext applicationContext;

	private static Logger logger = LoggerFactory.getLogger(UserUtils.class);

	public static SysUserEntity getCurentUser() {
		try {
			SysUserEntity sysUserEntity = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal());
			if (sysUserEntity == null) {
				sysUserEntity = getTokenUser();
			}
			return sysUserEntity;
		} catch (Exception e) {
			return null;
		}

	}

	public static Long getMallUserId() {
		SysUserEntity user = getCurentUser();
		return user.getMallUserId();
	}

	public static Long getUserId() {
		SysUserEntity user = getCurentUser();
		return user.getUserId();
	}

	public static SysUserEntity getTokenUser() {
		try {
			RedisTokenManager redisTokenManager = (RedisTokenManager) applicationContext.getBean("redisTokenManager");
			HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
			String token = request.getHeader("token");
			return redisTokenManager.getUserInfoBToken(token);
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
